﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using MongoDB.Bson;
using MongoDB.Driver;
using System.Collections.Generic;
using YDT.EBusines.Models;

namespace YDT.EBusines.Services
{
    /// <summary>
    /// 商品服务实现
    /// </summary>
    public class ProductService : IProductService
    {
        private readonly IMongoCollection<Product> _products;

        public ProductService(
            /* IMongoCollection<Product> products,*/
            IConfiguration configuration, IOptions<ProductMongoDBOptions> options)
        {
            // 1、建立MongoDB连接
            //var client = new MongoClient("mongodb://20.119.74.247:20525");

            //var client = new MongoClient("mongodb://192.168.211.132:20525");
            // MongoDB连接字符串（包含用户名和密码）

            //// MongoDB连接字符串（包含用户名和密码）
            //string connectionString = "mongodb://bobo:123456@20.119.74.247:27017,20.119.74.247:27018,20.119.74.247:27019/ProductDb?ssl=true&replicaSet=myrs";

            //// 创建客户端设置
            //var clientSettings = MongoClientSettings.FromConnectionString(connectionString);

            //var client = new MongoClient(clientSettings);

            //建立集群连接 复制集群
            //var client = new MongoClient("mongodb://bobo:123456@192.168.211.132:27017,192.168.211.132:27018,192.168.211.132:27019/ProductDb?replicaSet=myrs");
            //优先从 从节点读取数据 读写分离
            //client.WithReadPreference(ReadPreference.SecondaryPreferred);
            // 2、获取商品库(自己创建商品数据) 分片集群
            //var client = new MongoClient("mongodb://myroot:123456@192.168.211.132:27017,192.168.211.132:27117/admin()");
            var client = new MongoClient("mongodb://myroot:123456@192.168.211.132:27017,192.168.211.132:27117/admin()");
            var database = client.GetDatabase("articledb");
            //优先从 从节点读取数据 读写分离
            //client.WithReadPreference(ReadPreference.SecondaryPreferred);
            // 2、获取商品库(自己创建商品数据) 分片集群
            //var client = new MongoClient("mongodb://myroot:123456@192.168.211.132:27017,192.168.211.132:27117/admin()");
            //var client = new MongoClient("mongodb://bobo:123456@192.168.211.132:27017,192.168.211.132:27117/ProductDb");
            //var database = client.GetDatabase("ProductDb");

            // 3、获取商品表(自己创建商品数)Product
            _products = database.GetCollection<Product>("Product");

            // _products = products;
        }

        public void Create(Product _Product)
        {
            ObjectId newObjectId = ObjectId.GenerateNewId();
            _Product.Id = newObjectId.ToString();
            _products.InsertOne(_Product);
        }

        public void CreateList(List<Product> Products)
        {
            foreach (var Product in Products)
            {
                ObjectId newObjectId = ObjectId.GenerateNewId();
                Product.Id = newObjectId.ToString();
            }
            _products.InsertMany(Products);
        }

        public void Delete(Product Product)
        {
            _products.DeleteOne(product => product.Id == Product.Id);
        }

        public void DeleteList(Product Product)
        {
            _products.DeleteMany(product => product.Id == Product.Id);
        }

        public Product GetProductById(string id)
        {
            // 构建查询过滤器（可选）
            // 构建投影，只选择Name和Age字段
            var projection = Builders<Product>.Projection
                .Include(s => s.ProductTitle)
                .Include(s => s.ProductCode);
            //获取数据
            //var xw = _products.Find<BsonDocument>();
            return _products.Find<Product>(product => product.Id == id).Project<Product>(Builders<Product>.Projection.Include(s => s.ProductTitle).Include(s => s.ProductCode)).FirstOrDefault();
        }

        public  IEnumerable<Product> GetProducts()
        {
            //var filter = new BsonDocument(); // 替换为您要筛选的班级名称
            //// 注意：这里的"yourFieldName"和"yourFieldValue"应该替换为实际的字段名和字段值

            //// 执行查询并获取结果
            //var results =  _products.Find(filter).ToListAsync().Result;

            // 处理结果
            //foreach (var doc in results)
            //{
            //    // 输出整个文档（以JSON格式）
            //    //Console.WriteLine(doc.ToJson());

            //    // 或者，你可以访问特定的字段
            //    //var specificField = doc.AsString;
            //    //// 注意：这里的"yourFieldName"应该替换为实际的字段名，并且你需要检查字段是否存在以及它的类型是否正确
            //    //Console.WriteLine($"Value of 'yourFieldName': {specificField}");
            //}
            return _products.Find(product => true).ToList();
        }

        /*/// <summary>
        /// 商品数量查询
        /// </summary>
        /// <param name="id"></param>
        /// <param name="Product"></param>
        public long GetCount(int Page, int PageSize)
        {
            var skip = (Page - 1) * PageSize;
            return _products.Count();
        }*/

        /// <summary>
        /// 商品分页查询
        /// </summary>
        /// <param name="id"></param>
        /// <param name="Product"></param>
        public IEnumerable<Product> GetProductsByPage(int Page, int PageSize)
        {
            var skip = (Page - 1) * PageSize;
            return _products.Find(x => true).Skip(skip).Limit(PageSize).ToList();
        }

        /// <summary>
        /// 商品排序
        /// </summary>
        /// <param name="id"></param>
        /// <param name="Product"></param>
        public IEnumerable<Product> GetProductsBySort(Product product, int Page, int PageSize)
        {
            var skip = (Page - 1) * PageSize;
            return _products.Find(product => true).SortBy(product => product.ProductSort).ToList();
        }

        /// <summary>
        /// 商品价格聚合查询
        /// </summary>
        /// <param name="id"></param>
        /// <param name="Product"></param>
        public IEnumerable<int> GetProductsByAggregation(Product product)
        {
            //var filter = Builders<Product>.Filter.Eq(s => s.ProductTitle, "string"); // 筛选班级
            //filter = Builders<Product>.Filter.Or(filter, Builders<Product>.Filter.Eq(s => s.ProductCode, "哈哈"));
            //var ww = filter.ToBsonDocument();
            var te =  _products.AsQueryable().Sum(s => s.ProductPrice);
            var pipeline = new[]
              {
                  // new BsonDocument("$match", new BsonDocument
                  //{
                  //     { "class", "" }, // 班级筛选
                  //     { "score", new BsonDocument("$gte", "") } // 最低分数筛选
                  //}),
                 /* new BsonDocument("$match", new BsonDocument("ProductCode", "123rwe")), */// 筛选指定班级
                  //new BsonDocument("$match", filter.ToBsonDocument()), // 应用筛选条件
                  //new BsonDocument("$match", new BsonDocument("ProductTitle", "string")), // 筛选指定班级
                  new BsonDocument("$group", new BsonDocument
                  {

                        { "_id", BsonNull.Value },
                        { "totalProductPrice", new BsonDocument("$sum", "$ProductPrice") }
                  })
            };

            var result = _products.Aggregate<BsonDocument>(pipeline).FirstOrDefaultAsync().Result;
            var xw = result?["totalProductPrice"];
            Console.WriteLine(xw);
            //PipelineDefinition<Product, int> pipelineDefinitions = PipelineDefinition<Product, int>.Create("ProductPrice");
            //var ints = _products.Aggregate<int>(pipelineDefinitions);
            //while (ints.MoveNext())
            //{
            //    var test = ints.Current;
            //    return test;
            //}
            return null;
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id"></param>
        /// <param name="Product"></param>
        public void Update(string id, Product Product)
        {
            //var filter = Builders<Product>.Filter;
            var update = Builders<Product>.Update;
            //update.AddToSet("tonytest", "123123");
            //update.Set("ProductTitle", Product.ProductTitle)
            //_products.UpdateOne(product => product.Id == "6761212f1c617dedc1f8f144", update.AddToSet("wwwxx", "啦啦啦啦啦啦"));

            _products.UpdateOne(product => product.Id == "6761212f1c617dedc1f8f144", update.Set("Eamaill", "啦啦啦啦啦啦"));
            //_products.UpdateOne(product => product.Id == id, update.AddToSet("tonytest", "123123"));
        }

        /// <summary>
        /// 批量更新
        /// </summary>
        /// <param name="id"></param>
        /// <param name="Product"></param>
        public void UpdateList(string id, Product Product)
        {
            //var filter = Builders<Product>.Filter;
            var update = Builders<Product>.Update;
            _products.UpdateMany(product => true, update.Set("ProductPrice", 28));
        }

        /// <summary>
        /// 创建索引
        /// </summary>
        /// <returns></returns>
        public string CreateIndex()
        {
            var indexKeys = Builders<Product>.IndexKeys;
            return _products.Indexes.CreateOne(indexKeys.Descending("ProductCode"));
        }

        // 原理
        // 分片集群
        // 分片复制集群

        /// <summary>
        /// 替换
        /// </summary>
        /// <param name="id"></param>
        /// <param name="Product"></param>
        public void Replace(string id, Product Product)
        {
            _products.ReplaceOneAsync(x => x.Id == id, Product);
        }

        public bool ProductExists(string id)
        {
            Product product = _products.Find<Product>(product => product.Id == id).FirstOrDefault();
            if (product != null)
            {
                return true;
            }
            return false;
        }
    }
}
